package logger

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/mcuadros/go-defaults"
	"gopkg.in/natefinch/lumberjack.v2"
)

var (
	logger      *log.Logger
	infoLogger  *log.Logger
	warnLogger  *log.Logger
	errorLogger *log.Logger
)

func Init(logConfig *Logger) error {
	defaults.SetDefaults(logConfig)
	dir := filepath.Dir(logConfig.FPath)
	os.MkdirAll(dir, 0755)

	// 生成当天的日志文件名
	today := time.Now().Format("2006-01-02")
	logPath := filepath.Join(dir, today+".log")

	// 配置 lumberjack
	lumberjackLogger := &lumberjack.Logger{
		Filename:   logPath,
		MaxSize:    logConfig.MaxMB, // 文件大小超过时也会分割
		MaxAge:     logConfig.Days,  // 保留3天
		MaxBackups: logConfig.Days,  // 最多3个备份
		Compress:   true,            // 压缩旧日志
	}
	logger = log.New(lumberjackLogger, "", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	infoLogger = log.New(lumberjackLogger, "[INFO] ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	warnLogger = log.New(lumberjackLogger, "[WARN] ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	errorLogger = log.New(io.MultiWriter(lumberjackLogger, os.Stdout), "[ERROR] ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	return nil
}

func GetLogger() *log.Logger {
	return logger
}

func Info(v ...interface{}) {
	if len(v) <= 1 {
		infoLogger.Println(v...)
	} else {
		infoLogger.Printf(v[0].(string), v[1:]...)
		infoLogger.Println('\n')
	}
}

func Warn(v ...interface{}) {
	if len(v) <= 1 {
		warnLogger.Println(v...)
	} else {
		warnLogger.Printf(v[0].(string), v[1:]...)
		warnLogger.Println('\n')
	}
}

func Error(v ...interface{}) {
	if len(v) <= 1 {
		errorLogger.Println(v...)
	} else {
		errorLogger.Printf(v[0].(string), v[1:]...)
		errorLogger.Println('\n')
	}
}
